//
//  CHWebCommon.swift
//  bridging_js
//
//  Created by cyptt on 2021/8/9.
//

import UIKit
import WebKit
let CHWEB_CALL_DATA = "data";
let  CHWEB_CALL_MSG = "msg";
let CHWEB_CALL_RESULT = "result";
 let CALL_BACK_ACTIVE_NAME = "callbackActiveName";
class CHWebCommon: NSObject {

    
    
    /**
     对外
     */
   static func sendJsResultContent(webView: WKWebView,responseObject:Any,callbackActiveName:String, isSucess:Bool)  {
        var callDic:[String: Any] = [:]
        if (isSucess) {
            callDic = CHWebCommon.callSuccessDataDic(data:responseObject,callbackActiveName: callbackActiveName);
        }else{
            callDic  = CHWebCommon.callFailMessage(msg: responseObject as! String,callbackActiveName: callbackActiveName)
        }
    
      let result:String? = CHStringTool.dicValueString(callDic)
      CHWebCommon.callBack(webView: webView,  content: result!)
    }
    
    /**
     回调给js
     */
  static public func callBack(webView:WKWebView,content:String)  {
       
        let result:String? = content
    
    if ((result?.hasPrefix("base64")) == nil) {
        print("-----call----",result!)
    }
  
    print("---Thread--",Thread.current)
    print("-----call----",result!)

    if Thread.isMainThread {
        let c_funcName = jsCallBackName+"('" + result!  + "')"
        webView.evaluateJavaScript(c_funcName) { (any,err) in
            if(err != nil){
                print(err!)
            }
        }
    }else{
        
        DispatchQueue.main.async {
            let c_funcName = jsCallBackName+"('" + result!  + "')"
            webView.evaluateJavaScript(c_funcName) { (any,err) in
                if(err != nil){
                    print(err!)
                }
            }
        }
    }
        
    }
   
    
    
    
    /**
     成功
     */
    static func callSuccessDataDic(data:Any,callbackActiveName:String) -> Dictionary<String, Any> {
        
        var paramDic:[String: Any] = [:]
        paramDic[CHWEB_CALL_DATA] = data
        paramDic[CHWEB_CALL_MSG] = "成功"
        paramDic[CHWEB_CALL_RESULT]  = true;
        paramDic[CALL_BACK_ACTIVE_NAME] = callbackActiveName
        
        return paramDic
    }
    
    /**
     失败
     */
     static  func callFailMessage(msg:String,callbackActiveName:String)-> Dictionary<String, Any>{
        var paramDic:[String: Any] = [:]
        paramDic[CHWEB_CALL_DATA] = ""
        paramDic[CHWEB_CALL_MSG] = msg
        paramDic[CHWEB_CALL_RESULT]  = false;
        paramDic[CALL_BACK_ACTIVE_NAME] = callbackActiveName;
        return paramDic
    }
    
}
